const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron');
const path = require('path');
const fs = require('fs-extra');
const ncmdump = require('ncmdump');
const ffmpeg = require('fluent-ffmpeg');

let mainWindow;

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    },
    icon: path.join(__dirname, '../assets/icon.png'),
    titleBarStyle: 'default',
    resizable: true
  });

  mainWindow.loadFile('src/index.html');
  
  if (process.env.NODE_ENV === 'development') {
    mainWindow.webContents.openDevTools();
  }
}

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// IPC通信处理
ipcMain.handle('select-output-folder', async () => {
  const result = await dialog.showOpenDialog(mainWindow, {
    properties: ['openDirectory']
  });
  return result.filePaths[0];
});

ipcMain.handle('convert-files', async (event, files, outputFormat, outputFolder) => {
  const results = [];
  
  for (const file of files) {
    try {
      const result = await convertNCM(file, outputFormat, outputFolder, (progress) => {
        event.sender.send('conversion-progress', { file, progress });
      });
      results.push({ file, success: true, output: result });
    } catch (error) {
      results.push({ file, success: false, error: error.message });
    }
  }
  
  return results;
});

ipcMain.handle('open-folder', async (event, folderPath) => {
  shell.openPath(folderPath);
});

async function convertNCM(inputPath, outputFormat, outputFolder, onProgress) {
  return new Promise((resolve, reject) => {
    const filename = path.basename(inputPath, '.ncm');
    const outputPath = path.join(outputFolder, `${filename}.${outputFormat}`);
    
    // 使用ncmdump解密
    ncmdump(inputPath, outputFolder)
      .then((decryptedPath) => {
        // 如果已经是目标格式，直接返回
        if (path.extname(decryptedPath).toLowerCase() === `.${outputFormat}`) {
          onProgress(100);
          resolve(decryptedPath);
          return;
        }
        
        // 使用ffmpeg转换格式
        ffmpeg(decryptedPath)
          .toFormat(outputFormat)
          .audioBitrate(outputFormat === 'flac' ? 1411 : 320)
          .on('progress', (progress) => {
            onProgress(Math.round(progress.percent));
          })
          .on('end', () => {
            // 删除临时解密文件
            fs.unlinkSync(decryptedPath);
            onProgress(100);
            resolve(outputPath);
          })
          .on('error', (err) => {
            reject(new Error(`转换失败: ${err.message}`));
          })
          .save(outputPath);
      })
      .catch((err) => {
        reject(new Error(`解密失败: ${err.message}`));
      });
  });
}
